using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Xml.Serialization;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Google.GData.Calendar;
using Google.GData.Client;
using Microsoft.WindowsMobile.PocketOutlook;
using PocketGCal.code;

namespace PocketGCal
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        public config Configuration;
        

        private void menuItem3_Click(object sender, EventArgs e)
        {


            // Update the status bar to let users know what is going on
            SyncStatus.Text = "Connecting...";
            SyncStatus.Refresh();
            
            // need to get at the gdata web request to make the progress bar real
            menuItem3.Enabled = false;
            
            // set login
            GoogleCalendar.UserName = txtUsername.Text;
            GoogleCalendar.Password = txtPassword.Text;

            foreach (GFeed feed in GoogleCalendar.Feeds)
            {

                // build query

                EventFeed calFeed = null;
                // execute
                try
                {
                    // update the status
                    SyncStatus.Text = "Downloading...";
                    SyncStatus.Refresh();

                    calFeed = feed.GetEventFeed();

                    // open POOM session
                    OutlookSession olSess = new OutlookSession();

                    // create two colls of ol appointments, ones with and without google id
                    OutlookAppointments ogApps = new OutlookAppointments(olSess.Appointments.Items, true);
                    OutlookAppointments oApps = new OutlookAppointments(olSess.Appointments.Items, false);


                    // update status bar
                    SyncStatus.Text = "Syncing with Outlook...";
                    SyncStatus.Refresh();

                    // add or update entries in outlook from google
                    foreach (EventEntry gApp in calFeed.Entries)
                    {
                        Appointment oApp = ogApps.GetById(gApp.Id.AbsoluteUri);
                        if (oApp != null)
                        {
                            GoBetween.GoogleToOutlook(gApp, oApp, feed);
                        }
                        else
                        {
                            GoBetween.AddGoogleToOutlook(gApp, olSess, feed);
                        }
                    }

                    // update status bar
                    SyncStatus.Text = "Syncing back to Google...";
                    SyncStatus.Refresh();

                    // add new outlook appointments to google
                    foreach (Appointment oApp in oApps)
                    {
                        GoBetween.AddOutlookToGoogle(oApp, feed);
                    }

                }
                catch (Google.GData.Client.GDataForbiddenException)
                {
                    MessageBox.Show("Login error");
                }
                catch (Google.GData.Client.GDataRequestException)
                {
                    MessageBox.Show("Connection Error");
                }
                catch (SystemException)
                {

                }
            }

            menuItem3.Enabled = true;

            // clear the status bar
            SyncStatus.Text = "Idle";
            SyncStatus.Refresh();

        }


        private void menuItem2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void RememberMe_CheckStateChanged(object sender, EventArgs e)
        {
//            FileInfo creds;
//            StreamWriter fout;
            TextWriter w;

            String fullpath = System.Reflection.Assembly.GetExecutingAssembly().FullName;
            String configfile = System.IO.Path.GetDirectoryName(fullpath) + "/config.xml";

            XmlSerializer s = new XmlSerializer(typeof(config));

                try
                {
                    w = new StreamWriter(configfile);
                }
                catch
                {
                    chkRemember.Checked = false;
                    return;
                }

            if (chkRemember.Checked)    // Its been checked, so save the credentials
            {
                try
                {
                    Configuration.Username = txtUsername.Text;
                    Configuration.Password = txtPassword.Text;
                    Configuration.Remember = chkRemember.Checked;

                    // Serialization
                    s.Serialize(w, Configuration);
                    w.Close();
                }
                catch
                {
                    MessageBox.Show("Unable to save user info", "Error");
                    return;
                }

            }
            
            if( ! chkRemember.Checked)
            {
                try
                {
//                    creds.Delete(); // easy way to forget the credentials
                }
                catch
                {
                    MessageBox.Show("Unable to delete user info", "Error");
                    return;
                }

            }

        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Configuration = new config();  // create a new configuration object
            XmlSerializer s = new XmlSerializer(typeof(config));

            String fullpath = System.Reflection.Assembly.GetExecutingAssembly().FullName;
            String configfile = System.IO.Path.GetDirectoryName(fullpath)+"/config.xml";

            //picLogo.Image = (Bitmap)new System.Resources.ResourceManager("PocketGCal",GetType().Assembly).GetObject("logo.gif");
//            FileInfo creds;
//            StreamReader fin;

            picLogo.Width = this.Width;
            this.Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
            this.Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;

            // if we have a landscape screen, we need to remove the logo
            // so that we can see the status messages...

            if (this.Height < 300)
            {
                picLogo.Hide();
                txtPassword.Top -= 55;
                txtUsername.Top -= 55;
                UsernameLabel.Top -= 55;
                PasswordLabel.Top -= 55;
                chkRemember.Top -= 55;
                SyncStatus.Top -= 55;

            }

            try
            {
                // Deserialization
                TextReader r = new StreamReader(configfile);
                Configuration = (config)s.Deserialize(r);
                r.Close();

                txtUsername.Text = Configuration.Username;
                txtPassword.Text = Configuration.Password;
                chkRemember.Checked = Configuration.Remember;
            }
            catch       // if there is an error, ignore the stored user info
            {
                return;
            }


        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }


    }
}
